package com.github.shuaidd.rest.runtime;

import com.github.shuaidd.model.execption.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.activiti.app.model.runtime.CreateTaskRepresentation;
import org.activiti.app.model.runtime.TaskRepresentation;
import org.activiti.app.security.SecurityUtils;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("app")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TasksResource {

    private final TaskService taskService;

    @RequestMapping(value = "/rest/tasks", method = RequestMethod.POST)
    public TaskRepresentation createNewTask(@RequestBody CreateTaskRepresentation taskRepresentation, HttpServletRequest request) {
        if (StringUtils.isEmpty(taskRepresentation.getName())) {
            throw new BadRequestException("Task name is required");
        }

        Task task = taskService.newTask();
        task.setName(taskRepresentation.getName());
        task.setDescription(taskRepresentation.getDescription());
        if (StringUtils.isNotEmpty(taskRepresentation.getCategory())) {
            task.setCategory(taskRepresentation.getCategory());
        }
        task.setAssignee(SecurityUtils.getCurrentUserId());
        taskService.saveTask(task);
        return new TaskRepresentation(taskService.createTaskQuery().taskId(task.getId()).singleResult());
    }

}
